#include "Share.hpp"
#include <cstring>

#define LINE_SIZE 1024

enum{
    WRITTING_NORMAL = 1,
    WRITTING_CLOSE = 0,
    WRITTING_ERR = -1
};

//C风格-写入信息
int WrittingCType(int &fd){
    char line[LINE_SIZE] = {0};

    //读取信息
    printf("Enter a message of text: ");
    fgets(line, sizeof(line), stdin);

    //是否退出
    if(strcmp("quit\n", line) == 0){
        return WRITTING_CLOSE;
    }

    //写入信息
    ssize_t bytes_written = write(fd, line, strlen(line));

    if(bytes_written == -1){
        return WRITTING_ERR;
    }else{
        return WRITTING_NORMAL;
    }
}

//CPP风格-写入信息
int WrittingCPPType(int &fd){
    //获取信息
    std::string line;
    printf("Enter a message of text: ");
    std::getline(std::cin, line);

    //是否退出
    if(line == "quit"){
        return WRITTING_CLOSE;
    }

    ssize_t bytes_written = write(fd, line.c_str(), line.size());

    if(bytes_written == -1){
        return WRITTING_ERR;
    }else{
        return WRITTING_NORMAL;
    }
}

//客户端负责写
int main(){
    //打开管带-写
    int open_ret = open(NAMEDPIPE_PATH, O_WRONLY);
    if(open_ret == -1){
        perror("Failed to open");
        exit(FILE_OPEN_WRITE_ERR);
    }

    //进入循环读取信息
    while(true){
        // int listen_ret = WrittingCType(open_ret);
        int listen_ret = WrittingCPPType(open_ret);

        if(listen_ret == WRITTING_ERR || listen_ret == WRITTING_CLOSE){//写端关闭 或 出现意外
            break;
        }
    }

    close(open_ret);
    return 0;
}